<template>
	<view class="box">
		<uv-navbar placeholder title="新建地址" :autoBack="true"></uv-navbar>
		<view class="forms p-30">
			<uv-form labelPosition="left" labelWidth="130rpx" :model="formData" :rules="rules" ref="forms" :labelStyle="labelStyle">
				<uv-form-item label="地址" prop="regionName" borderBottom>
					<picker mode="region" @change="selecteProvinceCityArea">
						<view class="picker-view">
							<uv-input v-model="formData.regionName" disabled disabledColor="#FFF" border="none" placeholder="选择地址"></uv-input>
						</view>
					</picker>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item label="门牌号" prop="detail" borderBottom>
					<uv-input border="none" v-model="formData.detail" placeholder="详细地址，例:A座102室"></uv-input>
				</uv-form-item>
				<uv-form-item label="收件人" prop="name" borderBottom>
					<uv-input border="none" v-model="formData.name" placeholder="请输入联系人姓名"></uv-input>
				</uv-form-item>
				<uv-form-item label="联系电话" prop="phone" borderBottom>
					<uv-input border="none" type="number" maxlength="11" v-model="formData.phone" placeholder="请输入联系电话"></uv-input>
				</uv-form-item>
			</uv-form>
			<view class="m-t-30">
				<uv-checkbox-group v-model="checkboxValue" iconPlacement="right">
					<uv-checkbox activeColor="#830102" name="1" shape="square" label="设置为默认地址"></uv-checkbox>
				</uv-checkbox-group>
			</view>
		</view>
		<view class="fixed-bottom-50 m-x-30">
			<dy-button width="100%" @click="getRoute()">保存地址</dy-button>
			<view class="m-t-20">
				<dy-button width="100%" @click="getAddress()">同步微信地址</dy-button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { addEditAddress, getAddressDetail } from '@/api/api';
import regionPicker from '@/components/region-picker/region-picker.vue';
import { ref, onMounted, reactive, computed, components } from 'vue';
import { useStore } from 'vuex';
import { onReachBottom, onShow, onReady, onLoad } from '@dcloudio/uni-app';
import route from '@/uni_modules/uv-ui-tools/libs/util/route.js';
const forms = ref(null);
const rules = ref({
	detail: {
		type: 'string',
		required: true,
		trigger: ['blur', 'change'],
		validator: (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入门牌号'));
				return;
			}
			const pattern = /^[\u4e00-\u9fa5a-zA-Z0-9\-#室号]+$/;
			if (!pattern.test(value)) {
				callback(new Error('门牌号格式不正确'));
				return;
			}
			// if (!/\d/.test(value)) {
			// 	callback(new Error('门牌号需包含数字'));
			// 	return;
			// }
			if (value.length < 2 || value.length > 30) {
				callback(new Error('门牌号长度应在2-30个字符之间'));
				return;
			}
			callback();
		}
	},
	regionName: {
		type: 'string',
		required: true,
		message: '请选择省市区',
		trigger: ['blur', 'change']
	},
	name: {
		type: 'string',
		required: true,
		message: '请输入联系人姓名',
		trigger: ['blur', 'change']
	},
	phone: {
		type: 'string',
		required: true,
		trigger: ['blur', 'change'],
		validator: (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入联系电话'));
				return;
			}
			if (!/^\d+$/.test(value)) {
				callback(new Error('联系电话只能是数字'));
				return;
			}
			if (!/^1[3-9]\d{9}$/.test(value)) {
			  callback(new Error('请输入正确的手机号码'));
			  return;
			}
			callback();
		}
	}
});
const checkboxValue = ref([]); //默认地址  有值为默认地址
const address_id = ref(null); //地址id
const isSubmitting = ref(false); //防止重复点击
const formData = ref({
	name: '', //收件人
	detail: '', //门牌号
	phone: '', //联系电话
	region: '', //coed
	regionName: '', //省市区
	province: '', //省
	city: '', //市
	district: '' //区
});
// 获取地址
const getAddress = () => {
	console.log('1123');
	let that = this;
	uni.getSetting({
		success(res1) {
			uni.authorize({
				scope: 'scope.address',
				success() {
					uni.chooseAddress({
						success: function (res) {
							console.log('123', res);
							formData.value.detail = res.detailInfoNew;
							formData.value.phone = res.telNumber;
							formData.value.name = res.userName;
							formData.value.regionName = `${res.provinceName}-${res.cityName}-${res.countyName}`;
							formData.value.city = res.cityName;
							formData.value.district = res.countyName;
							formData.value.province = res.provinceName;
							formData.value.region = res.postalCode;
						},
						fail: (err) => {
							console.log(err, '123');
						}
					});
				},
				fail: (res) => {
					console.log(res);
					uni.showModal({
						title: '获取失败',
						content: '请开启授权我的地址权限',
						success(res) {
							uni.openSetting();
						}
					});
				}
			});
		},
		fail: function (err) {
			console.error(JSON.stringify(err));
		}
	});
};
//选择省市区
const selecteProvinceCityArea = (value, inx) => {
	console.log(value);
	formData.value.regionName = value.detail.value.join('-');
	formData.value.region = value.detail.code;
	formData.value.province = value.detail.value[0];
	formData.value.city = value.detail.value[1];
	formData.value.district = value.detail.value[2];
};
//保存地址
const getRoute = () => {
	// 防止重复点击
	if (isSubmitting.value) return;
	isSubmitting.value = true;

	forms.value
		.validate()
		.then((res) => {
			addEditAddress({
				...formData.value,
				is_default: checkboxValue.value.length > 0 ? 1 : 0,
				address_id: address_id.value
			}).then((res) => {
				console.log(res, '----------');
				if (res.code == 1) {
					uni.showToast({
						icon: 'none',
						title: '保存成功'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				} else {
					isSubmitting.value = false;
					uni.showToast({
						icon: 'none',
						title: res.msg
					});
				}
			});
		})
		.catch((errors) => {
			uni.showToast({
				icon: 'none',
				title: errors[0].message
			});
			isSubmitting.value = false;
		});
};
onLoad((options) => {
	if (options.address_id) {
		address_id.value = options.address_id;
		getAddressDetail({ address_id: options.address_id }).then((res) => {
			console.log(res, '----------');
			if (res.code == 1) {
				formData.value = res.data;
				formData.value.regionName = res.data.province + '-' + res.data.city + '-' + res.data.district;
				checkboxValue.value = [res.data.is_default == 1 ? '1' : '0'];
			}
		});
	}
});
</script>

<style lang="scss" scoped>
::v-deep .uv-checkbox__label-wrap {
	margin-right: 10rpx !important;
	margin-left: 0 !important;
	padding-left: 0 !important;
}

.box {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding: 25rpx 32rpx;
	box-sizing: border-box;
}

.forms {
	width: 686rpx;
	// height: 541rpx;
	background: #fff;
	border-radius: 12rpx;
}
</style>
